﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using Windows.Data.Xml.Dom;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.Storage;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Media.Imaging;
using Windows.UI.Xaml.Navigation;


namespace IMDB
{

    public sealed partial class MainPage : Page
    {
        private static HttpClient httpClient;
        private static HttpClientHandler handler;

        public MainPage()
        {
            this.InitializeComponent();
            //this.MainBorder.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
            GetHistory();
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {

        }

        private async void GetHistory()
        {
            HistoryLabel.Text = "Loading History...";
            StorageFolder folder=ApplicationData.Current.LocalFolder;
            List<movie> movies = new List<movie>();
            try
            {
                StorageFile file = await folder.GetFileAsync("History.txt");
                if (file != null)
                {
                    string wholeName = await FileIO.ReadTextAsync(file);
                    string[] name = wholeName.Split(',');
                    

                    for (int i = 0; i < name.Length; i++)
                    {
                        handler = new HttpClientHandler();
                        handler.AllowAutoRedirect = false;
                        httpClient = new HttpClient(handler);
                        httpClient.MaxResponseContentBufferSize = 256000;
                        httpClient.DefaultRequestHeaders.Add("user-agent", "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)");
                        string url = "http://imdbapi.org/?title=" + name[i] + "&type=xml&plot=full&release=simple";
                        try
                        {
                            HttpResponseMessage response = await httpClient.GetAsync(url);
                            response.EnsureSuccessStatusCode();
                            string responseBodyAsText = await response.Content.ReadAsStringAsync();

                            XmlDocument doc = new XmlDocument();
                            doc.LoadXml(responseBodyAsText);

                            movies.Add(new movie
                            {
                                title = doc.SelectSingleNode("//title").InnerText,
                                imageUrl = doc.SelectSingleNode("//poster").InnerText,
                                plot = doc.SelectSingleNode("//plot_simple").InnerText
                            });
                        }
                        catch (HttpRequestException hre)
                        {

                        }
                        catch (Exception ex)
                        {

                        }
                    }
                    if (movies.Count > 0)
                    {
                        movies.Reverse();
                    }
                }
            }
            catch (Exception e)
            { 
                
            }
            HistoryListBox.ItemsSource = movies;
            HistoryLabel.Text = "Your Search History";
        }

        private void ProcessResult(string result)
        {
            ClearLastValue();

            XmlDocument doc = new XmlDocument();
            doc.LoadXml(result);

            // process title
            this.BodyTitle.Text = doc.SelectSingleNode("//title").InnerText;

            // process poster
            this.BodyImage.Source = new BitmapImage(new Uri(doc.SelectSingleNode("//poster").InnerText));

            // process plot
            this.BodyPlot.Text = doc.SelectSingleNode("//plot").InnerText;

            // process simple plot
            this.BodyPlotSimple.Text = doc.SelectSingleNode("//plot_simple").InnerText;

            // process rating
            this.BodyRate.Text = doc.SelectSingleNode("//rating").InnerText;

            // process year
            this.BodyYear.Text = doc.SelectSingleNode("//year").InnerText;

            // process runtime
            this.BodyRuntime.Text = doc.SelectSingleNode("//runtime").InnerText;

            // process release
            this.BodyRelease.Text = doc.SelectSingleNode("//release_date").InnerText.Insert(4, ".").Insert(7,".");
            

            // process director          
            XmlNodeList directorsList = doc.SelectNodes("//directors/item");
            foreach(XmlElement node in directorsList)
            {
                this.BodyDirector.Text += node.InnerText + ", "; 
            }

            // process star
            XmlNodeList starsList = doc.SelectNodes("//actors/item");
            if (starsList.Length > 3)
            {
                for (int i = 0; i < 3; i++)
                {
                    this.BodyStar.Text += starsList[i].InnerText + ", ";
                }
            }
            else
            {
                foreach (XmlElement node in starsList)
                {
                    this.BodyStar.Text += node.InnerText + ", ";
                }
            }

            // process genres
            XmlNodeList genresList = doc.SelectNodes("//genres/item");
            foreach (XmlElement node in genresList)
            {
                this.BodyGenres.Text += node.InnerText + ", ";
            }

        }

        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            ClearLastValue();
            StartSearch();
        }

        private async void StartSearch()
        {
            handler = new HttpClientHandler();
            handler.AllowAutoRedirect = false;
            httpClient = new HttpClient(handler);
            httpClient.MaxResponseContentBufferSize = 256000;
            httpClient.DefaultRequestHeaders.Add("user-agent", "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)");

            string url = "http://imdbapi.org/?title=" + textboxone.Text + "&type=xml&plot=full&release=simple";

            SaveHistory();

            try
            {
                HttpResponseMessage response = await httpClient.GetAsync(url);
                response.EnsureSuccessStatusCode();
                string responseBodyAsText = await response.Content.ReadAsStringAsync();
                ProcessResult(responseBodyAsText);
            }
            catch (HttpRequestException hre)
            {

            }
            catch (Exception ex)
            {

            }
        }

        private async void SaveHistory()
        {
            StorageFolder folder = ApplicationData.Current.LocalFolder;
            StorageFile file = await folder.CreateFileAsync("History.txt", CreationCollisionOption.OpenIfExists);

            try
            {
                if (file != null)
                {
                    string wholeName = await FileIO.ReadTextAsync(file);
                    string[] name = wholeName.Split(',');

                    
                    for (int i = 0; i < name.Length; i++)
                    {
                        if (textboxone.Text == name[i])
                        {
                            return;
                        }
                    }
                    await FileIO.AppendTextAsync(file, textboxone.Text + ",");
                }
            }
            catch (Exception e)
            { 
            
            }    
            
        }

        private void ClearLastValue()
        {
            this.BodyGenres.Text = "";
            this.BodyDirector.Text = "";
            this.BodyStar.Text = "";
        }

        private void HistoryListBox_ItemClick(object sender, ItemClickEventArgs e)
        {
            //ListViewItem item = (ListViewItem)e.ClickedItem;
            movie m = (movie)e.ClickedItem;

            RefreshMainPanel(m.title);            
            
        }

        private async void RefreshMainPanel(string title)
        {
            handler = new HttpClientHandler();
            handler.AllowAutoRedirect = false;
            httpClient = new HttpClient(handler);
            httpClient.MaxResponseContentBufferSize = 256000;
            httpClient.DefaultRequestHeaders.Add("user-agent", "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)");

            string url = "http://imdbapi.org/?title=" + title + "&type=xml&plot=full&release=simple";
            try
            {
                HttpResponseMessage response = await httpClient.GetAsync(url);
                response.EnsureSuccessStatusCode();
                string responseBodyAsText = await response.Content.ReadAsStringAsync();
                ProcessResult(responseBodyAsText);
            }
            catch (HttpRequestException hre)
            {

            }
            catch (Exception ex)
            {

            }
        }
    }
}
